using System;

// 环形数组测试类
public class CircularArrayTest
{
    //将array改造为环形数组
    private DyArray<int> array;
    private int startIndex = 0;
    public int count = 0;
    private int capacity => array.GetLength();

    public CircularArrayTest()
    {
        array = new(5);
        array.AddValueFast(new int[] { 1, 2, 3, 4, 5 });
        count = array.Count;
        startIndex = 0;
    }

    public static void RunTest()
    {
        CircularArrayTest circularArray = new CircularArrayTest();

        Console.WriteLine("===========拿到第一个元素 以测试映射===========:" + circularArray.Get(0));

        Console.WriteLine("\n按 Enter 键继续测试...");
        Console.ReadLine();

        circularArray.RotateLeft();
        Console.WriteLine("======================");
        for (int i = 0; i < circularArray.count; i++)
        {
            Console.WriteLine("第" + i + "个元素:" + circularArray.Get(i));
        }

        Console.WriteLine("\n按 Enter 键继续测试...");
        Console.ReadLine();

        circularArray.RotateRight();
        Console.WriteLine("===========向右旋转一个位置:===========");
        for (int i = 0; i < circularArray.count; i++)
        {
            Console.WriteLine("第" + i + "个元素:" + circularArray.Get(i));
        }
    }

    /// <summary>
    /// 映射索引
    /// </summary>
    /// <param name="i">i是实际索引，取值范围是0到capacity-1</param>
    /// <returns></returns>
    private int Map(int i)
    {
        if (i < 0 || i >= capacity) return -1;
        return (i + startIndex) % capacity;
    }

    public int Get(int i)
    {
        if (i < 0 || i >= count) return -1;
        return array.GetValueWithIndex(Map(i));
    }

    public void Set(int i, int value)
    {
        if (i < 0 || i >= count) return;
        array.SetValueWithIndex(Map(i), value);
    }

    /// <summary>
    /// 向左滑动k个位置
    /// </summary>
    /// <param name="k"></param>
    public void RotateLeft(int k = 1)
    {
        if (count == 0) return;
        k %= capacity;
        if (k < 0) k += capacity;
        startIndex = (startIndex + k) % capacity;
    }

    /// <summary>
    /// 向右滑动k个位置
    /// </summary>
    /// <param name="k"></param>
    public void RotateRight(int k = 1)
    {
        if (count == 0) return;
        k %= capacity;
        if (k < 0) k += capacity;
        startIndex = (startIndex - k + capacity) % capacity;
    }

    public bool Enqueue(int v)
    {
        if (count == capacity) return false;
        array.SetValueWithIndex(Map(count), v);
        count++;
        return true;
    }

    public bool Dequeue(out int v)
    {
        if (count == 0) { v = default; return false; }
        v = array.GetValueWithIndex(startIndex);
        startIndex = (startIndex + 1) % capacity;
        count--;
        return true;
    }
}
